import React, { Component, useEffect, useRef } from "react";
import { Form, Input, Button, Space, Radio } from "antd";
import { DeleteOutlined, EditOutlined } from "@ant-design/icons";
import TheButton from "@/components/TheButton";
// import {
//   SortableContainer,
//   SortableElement,
//   SortableHandle,
// } from "react-sortable-hoc";
import arrayMove from "array-move";
import TheDialog from "@/components/TheDialog";
// import enabled from "@/assets/icons/enabled.svg";
// import notEnabled from "@/assets/icons/notEnabled.svg";
import "./style/index.less";
import {
  apiGetProductClassifyOpenList,
  apiGetProductClassifyCloseList,
  apiGetProductClassifyBatchAdd,
  apiGetProductClassifyEdit,
  apiGetProductClassifyAdd,
  apiGetProductClassifyDel,
} from "@/request/mallConfig";
import { filtering } from "@/utils/regexp";

// const DragHandle = SortableHandle(() => (
//   <MenuOutlined style={{ cursor: "grab", color: "#999" }} />
// ));
// const SortableItem = SortableElement(
//   ({ value, onDel, onEdit, type, onEnabled }) => {
//     return (
//       <li>
//         <DragHandle />
//         <span>{value.productClassifyName}</span>
//         <div>
//           {/*<TheButton onClick={() => onEnabled(value)}>{<TheImage width={12.5}*/}
//           {/*                                                       src={type === 'enabled' ? enabled : notEnabled}/>}</TheButton>*/}
//           <TheButton auth={"category:update"} onClick={() => onEdit(value)}>
//             <EditOutlined />
//           </TheButton>
//           <TheButton auth={"category:delete"} onClick={() => onDel(value)}>
//             <DeleteOutlined />
//           </TheButton>
//         </div>
//       </li>
//     );
//   }
// );
const UlItem = ({ value, onDel, onEdit, type, onEnabled }) => {
  return (
    <li>
      <span>{value.productClassifyName}</span>
      <div>
        <TheButton haspermi={['commodity:update']} onClick={() => onEdit(value)}>
          <EditOutlined />
        </TheButton>
        <TheButton haspermi={['commodity:delete']}  onClick={() => onDel(value)}>
          <DeleteOutlined />
        </TheButton>
      </div>
    </li>
  );
}

// const SortableList = SortableContainer(({ children }) => {
//   return <>{children}</>;
// });

const Edit = ({ editValue, onFinish, dialogCancel }) => {
  const formRef = useRef();
  useEffect(() => {
    if (editValue) {
      formRef.current.setFieldsValue(editValue);
    }
  }, []);
  return (
    <Form ref={formRef} onFinish={onFinish}>
      <Form.Item
        rules={[
          { required: true },
          { max: 4 },
          { pattern: filtering, message: "名称不允许输入特殊字符或空格" },
        ]}
        name={"productClassifyName"}
        label={"名称"}
      >
        <Input maxLength={4} />
      </Form.Item>
      <Form.Item
        rules={[{ required: true }]}
        name={"productClassifyStatus"}
        label={"是否启用"}
      >
        <Radio.Group>
          <Radio value={"Y"}>是</Radio>
          <Radio value={"N"}>否</Radio>
        </Radio.Group>
      </Form.Item>
      <Form.Item>
        <Space style={{ display: "flex", justifyContent: "flex-end" }}>
          <Button onClick={dialogCancel}>取消</Button>
          <Button type={"primary"} htmlType={"submit"}>
            确认
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

class Category extends Component {
  state = {
    enabled: [],
    notEnabled: [],
    title: "",
    dialogStatus: false,
    editValue: null,
  };

  async componentDidMount() {
    await this.getEnabled();
    await this.getNotEnabled();
  }

  getEnabled = async () => {
    const response = await apiGetProductClassifyOpenList();
    if (response.code === 0) {
      this.setState({
        enabled: response.data,
      });
    }
  };
  getNotEnabled = async () => {
    const res = await apiGetProductClassifyCloseList();
    if (res.code === 0) {
      this.setState({
        notEnabled: res.data,
      });
    }
  };

  onEnabledSortEnd = ({ oldIndex, newIndex }) => {
    this.setState(
      ({ enabled }) => ({
        enabled: arrayMove(enabled, oldIndex, newIndex),
      }),
      async () => {
        const productClassify = this.state.enabled.map((v, i) => {
          return {
            ...v,
            sorted: i + 1,
          };
        });
        const res = await apiGetProductClassifyBatchAdd({
          productClassifyJson: JSON.stringify(productClassify),
        });
        if (res.code === 0) {
          await this.getEnabled();
        }
      }
    );
  };
  onNotEnabledSortEnd = ({ oldIndex, newIndex }) => {
    this.setState(
      ({ notEnabled }) => ({
        notEnabled: arrayMove(notEnabled, oldIndex, newIndex),
      }),
      async () => {
        const productClassify = this.state.notEnabled.map((v, i) => {
          return {
            ...v,
            sorted: i + 1,
          };
        });
        const res = await apiGetProductClassifyBatchAdd({
          productClassifyJson: JSON.stringify(productClassify),
        });
        if (res.code === 0) {
          await this.getNotEnabled();
        }
      }
    );
  };
  onDel = (value) => {
    React.$confirm({
      title: "确定删除此数据信息吗？",
      onOk: async () => {
        const response = await apiGetProductClassifyDel({
          productClassifyId: value.productClassifyId,
        });
        if (response.code === 0) {
          await this.getEnabled();
          await this.getNotEnabled();
          React.$message({
            type: "info",
            content: "删除成功",
          });
        }
      },
    });
  };
  onEdit = (value) => {
    if (value) {
      this.setState({
        dialogStatus: true,
        editValue: value,
        title: "修改类目",
      });
    } else {
      this.setState({
        dialogStatus: true,
        title: "新增类目",
      });
    }
  };
  dialogCancel = () => {
    this.setState({
      dialogStatus: false,
      editValue: null,
      title: "",
    });
  };
  onFinish = async (value) => {
    if (this.state.editValue) {
      value.productClassifyId = this.state.editValue.productClassifyId;
      const response = await apiGetProductClassifyEdit(value);
      if (response.code === 0) {
        this.dialogCancel();
        await this.getEnabled();
        await this.getNotEnabled();
        React.$message({
          type: "info",
          content: "修改成功",
        });
      }
    } else {
      const response = await apiGetProductClassifyAdd(value);
      if (response.code === 0) {
        this.dialogCancel();
        await this.getEnabled();
        await this.getNotEnabled();
        React.$message({
          type: "info",
          content: "新增成功",
        });
      }
    }
  };
  onEnabled = (value) => {
    if (value.productClassifyStatus === "Y") {
      React.$confirm({
        title: "确定停止启用该类目吗？",
        onOk: async () => {
          const res = await apiGetProductClassifyEdit({
            productClassifyId: value.productClassifyId,
            productClassifyStatus: "N",
          });
          if (res.code === 0) {
            await this.getEnabled();
          }
        },
      });
    }
  };

  render() {
    const { title, dialogStatus, editValue } = this.state;
    return (
      <div className={"p-layout-box"}>
        <div className={"p-layout-content"}>
          <div className={"mall-category-first"}>
            <TheButton
              onClick={() => this.onEdit()}
              size={"middle"}
              type={"default"}
              haspermi={['commodity:add']}
            >
              新增
            </TheButton>
            <div className={"category-content"}>
              {/* <UlItem onSortEnd={this.onEnabledSortEnd} useDragHandle> */}
                <ul className={"category-enabled"}>
                  <li>已启用类目</li>
                  {this.state.enabled.map((value, index) => {
                    return (
                      <UlItem
                        type={"enabled"}
                        onEdit={this.onEdit}
                        onDel={this.onDel}
                        onEnabled={this.onEnabled}
                        key={index}
                        index={index}
                        value={value}
                      />
                    );
                  })}
                </ul>
              {/* </UlItem> */}
              {/* <SortableList onSortEnd={this.onNotEnabledSortEnd} useDragHandle> */}
                <ul className={"category-enabled"}>
                  <li>未启用类目</li>
                  {this.state.notEnabled.map((value, index) => {
                    return (
                      <UlItem
                        type={"notEnabled"}
                        onEdit={this.onEdit}
                        onDel={this.onDel}
                        onEnabled={this.onEnabled}
                        key={index}
                        index={index}
                        value={value}
                      />
                    );
                  })}
                </ul>
              {/* </SortableList> */}
            </div>
          </div>
        </div>

        <TheDialog
          title={title}
          visible={dialogStatus}
          footer={null}
          handleCancel={this.dialogCancel}
        >
          <Edit
            onFinish={this.onFinish}
            dialogCancel={this.dialogCancel}
            editValue={editValue}
          />
        </TheDialog>
      </div>
    );
  }
}

export default Category;
